﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BartonExtension
{
    public static class IEnumulatorExtensions
    {
        public static bool ToCSV(this List<Dictionary<string,object>> data,string filename,List<string> header,List<string> caption)
        {
            try
            {
                string csv = "";
                //csv += "{0}\n".FormatWith(header);
                caption.ForEach(c =>
                {
                    csv += caption.Last().Equals(c) ? c : c + ",";
                });
                csv += "\n";
                for (int i = 0; i < data.Count; i++)
                {
                    header.ForEach(h =>
                        {
                            csv += header.Last().Equals(h) ? data[i][h].ToString() : data[i][h].ToString() + ",";
                        });
                    csv += "\n";
                }
                File.WriteAllText(filename, csv, Encoding.UTF8);
                return true;
            }
            catch(Exception e)
            {
                return false;
            }
        }
    }
}
